package com.smart.mac.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.mac.common.R;
import com.smart.mac.model.dto.FlowSaveXmlDTO;
import com.smart.mac.model.vo.FlowProcDefVO;
import com.smart.mac.service.FlowDefinitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 流程定义
 *
 * @Author mac
 */
@Slf4j
@RestController
@RequestMapping("/flowable/definition")
public class FlowDefinitionController {


    @Autowired
    private FlowDefinitionService flowDefinitionService;

    /**
    *  导入流程文件
    * @param: [name, category, file]
    * @return: com.elephant.demo.common.R
    * @author mac
    */
    @PostMapping("/import")
    public R importFile(@RequestParam String name,
                        @RequestParam(required = false) String category,
                        MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            flowDefinitionService.importFile(name, category, in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return R.failed(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }
        return R.ok("导入成功");
    }

    /**
    * 保存流程设计器内的xml文件
    * @param: [saveXmlDTO]
    * @return: com.elephant.demo.common.R
    * @author mac
    */
    @PostMapping("/save")
    public R  save(@RequestBody FlowSaveXmlDTO saveXmlDTO) {
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(saveXmlDTO.getXml().getBytes(StandardCharsets.UTF_8));
            flowDefinitionService.importFile(saveXmlDTO.getName(), saveXmlDTO.getCategory(), in);
        } catch (Exception e) {
            log.error("导入失败:", e);
            return R.failed(e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("关闭输入流出错", e);
            }
        }
        return  R.ok("保存流程成功");
    }

    /**
    * 读取图片
    * @param: [deployId, response]
    * @return: void
    * @author mac
    */
    @GetMapping("/readImage/{deployId}")
    public void readImage(@PathVariable(value = "deployId") String deployId, HttpServletResponse response) {
        OutputStream os = null;
        BufferedImage image = null;
        try {
            image = ImageIO.read(flowDefinitionService.readImage(deployId));
            response.setContentType("image/png");
            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "png", os);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
    * 发起流程
    * @param: [procDefId 流程定义ID, variables 变量]
    * @return: com.elephant.demo.common.R
    * @author mac
    */
    @PostMapping("/start/{procDefId}")
    public R start(@PathVariable(value = "procDefId") String procDefId,
                   @RequestBody Map<String, Object> variables) {
        return flowDefinitionService.startProcessInstanceById(procDefId, variables);
    }

    /**
    * 由流程key以及业务key开启流程
    * @param: [procDefKey 流程key, businessKey 业务key, variables]
    * @return: com.elephant.demo.common.R
    * @author mac
    */
    @PostMapping("/start/{procDefKey}/{businessKey}")
    public R startByKey(@PathVariable(value = "procDefKey") String procDefKey,
                   @PathVariable(value = "businessKey") String businessKey,
                   @RequestBody Map<String, Object> variables) {
        return flowDefinitionService.startProcessInstanceByKey(procDefKey, businessKey,variables);
    }

    /**
    * 激活或挂起流程定义
    * @param: [state 1:激活,2:挂起", deployId]
    * @return: com.elephant.demo.common.R
    * @author mac
    */
    @PutMapping(value = "/updateState")
    public R updateState(@RequestParam Integer state, @RequestParam String deployId) {
        flowDefinitionService.updateState(state, deployId);
        return R.ok("激活或挂起成功");
    }


    /**
    * 删除流程
    * @param: [deployIds]
    * @return: com.elephant.demo.common.R
    * @author mac
    */
    @DeleteMapping(value = "/{deployIds}")
    public R delete(@PathVariable String[] deployIds) {
        for (String deployId : deployIds) {
            flowDefinitionService.delete(deployId);
        }
        return R.ok("删除流程成功");
    }

    /**
    * 流程定义列表
    * @param: [pageNum, pageSize, name]
    * @return: com.elephant.demo.common.R
    * @author mac
    */
    @GetMapping(value = "/page")
    public R<Page<FlowProcDefVO>> page(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                       @RequestParam(required = false) String name) {
        return R.ok(flowDefinitionService.page(name, pageNum, pageSize));
    }




}
